//index.js
//获取应用实例
const app = getApp()
const { getArgs } = require('../../utils/util.js')

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    code: '',
    name: '',
    isSave: false
  },
  onLoad: function () {
    // 判断本地存储有没有code和name
    var userInfo = wx.getStorageSync('userInfo')
    userInfo.code && userInfo.name ? this.setData({isSave: true}) : '';

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
    // 将userInfo存进本次储存
    var userInfo = wx.getStorageSync('userInfo')
    userInfo.avatar = e.detail.userInfo.avatarUrl
    userInfo.wx_name = e.detail.userInfo.nickName
    wx.setStorageSync('userInfo', userInfo)
  },
  // 设置code
  setCodeFn (e) {
    let value = e.detail.value
    this.setData({
      code: value
    })
  },
  // 设置真实姓名
  setNameFn (e) {
    let value = e.detail.value
    this.setData({
      name: value
    })
  },
  // 表单提交
  submitFn (e) {
    if(!this.data.code) {
      wx.showModal({
        title: '提示',
        content: '请输入学号',
        showCancel: false
      })
      return false;
    }
    if (!this.data.name) {
      wx.showModal({
        title: '提示',
        content: '请输入真实姓名',
        showCancel: false
      })
      return false;
    }
    // 写进本地存储
    var userInfo = wx.getStorageSync('userInfo')
    console.log(this.data)
    userInfo.code = this.data.code
    userInfo.name = this.data.name
    wx.setStorageSync('userInfo', userInfo)
    // 新增学生
    wx.showLoading({
      title: '正在保存中...',
      mask: true
    })
    wx.request({
      url: 'https://wenye123.com/student/add',
      method: 'POST',
      data: {
        avatar: userInfo.avatar,
        wx_name: userInfo.wx_name,
        openid: userInfo.openId,
        code: this.data.code,
        name: this.data.name
      },
      success: res => {
        console.log(res)
        if (res.data.status === 'ok') {
          // 写进本地存储
          var userInfo = wx.getStorageSync('userInfo')
          userInfo.sid = res.data.data._id
          wx.setStorageSync('userInfo', userInfo)
          // 显示保存成功toast
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000
          })
          // 显示可以扫码的按钮
          this.setData({ isSave: true })
        } else {
          wx.showToast({
            title: '保存失败',
            duration: 2000
          })
        }
      }
    })
  },
  // 扫码新增
  scanCodeFn () {
    wx.scanCode({
      onlyFromCamera: true,
      success: function(res) {
        if (res.result.indexOf('wenye123.com') > -1) {
          let url = getArgs(res.result)
          // data
          let data = { sid: wx.getStorageSync('userInfo').sid }
          url.params.forEach(item => {
            data = Object.assign({}, data, { [item.key]: item.value })
          })

          // 新增学生
          wx.showLoading({
            title: 'loading...',
            mask: true
          })
          wx.request({
            url: url.path,
            method: 'POST',
            data: data,
            success: res => {
              console.log(res)
              wx.hideLoading()
              if (res.data.status === 'ok') {
                // 显示保存成功toast
                wx.showToast({
                  title: '签到成功',
                  icon: 'success',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: res.data.data,
                  duration: 2000
                })
              }
            }
          })
        }
      },
      fail: function(res) {
        wx.showToast({
          title: '扫码失败',
          icon: 'success',
          duration: 2000
        })
      }
    })
  }
})
